package org.chen.controller;

import lombok.RequiredArgsConstructor;
import org.chen.common.domain.R;
import org.chen.domain.dto.*;
import org.chen.domain.vo.CategoryVO;
import org.chen.service.CategoryService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/category")
@RequiredArgsConstructor
@Validated
public class CategoryController {
    
    private final CategoryService categoryService;
    
    @GetMapping("/tree")
    public R<List<CategoryVO>> getTree(@RequestParam String type) {
        return R.success(categoryService.getTreeByType(type));
    }

    @GetMapping("/list")
    public R<List<CategoryVO>> list(CategoryQueryDTO query) {
        return R.success(categoryService.list(query));
    }
    
    @GetMapping("/{id}")
    public R<CategoryVO> getById(@PathVariable String id) {
        return R.success(categoryService.getById(id));
    }

    @GetMapping("/batch")
    public R<List<CategoryVO>> getCategoriesByIds(@RequestParam List<String> ids) {
        return R.success(categoryService.getBatchByIds(ids));
    }
    
    @PostMapping
    public R<Void> add(@RequestBody @Validated CategoryDTO dto) {
        categoryService.add(dto);
        return R.success();
    }
    
    @PutMapping("/{id}")
    public R<Void> update(@PathVariable String id, @RequestBody @Validated CategoryDTO dto) {
        dto.setId(id);
        categoryService.update(dto);
        return R.success();
    }
    
    @DeleteMapping("/{id}")
    public R<Void> delete(@PathVariable String id) {
        categoryService.delete(id);
        return R.success();
    }

    @DeleteMapping("/batch")
    public R<Void> batchDelete(@RequestBody BatchDeleteDTO dto) {
        categoryService.batchDelete(dto.getIds());
        return R.success();
    }
    
    @PutMapping("/{id}/move")
    public R<Void> move(
        @PathVariable String id,
        @RequestParam String targetParentId) {
        categoryService.move(id, targetParentId);
        return R.success();
    }
    
    @GetMapping("/{id}/children")
    public R<List<CategoryVO>> getChildren(@PathVariable String id) {
        return R.success(categoryService.getChildren(id));
    }

    @GetMapping("/{id}/path")
    public R<String> getPath(@PathVariable String id) {
        return R.success(categoryService.getPath(id));
    }

    @PutMapping("/{id}/status")
    public R<Void> updateStatus(
            @PathVariable String id,
            @RequestBody @Validated CategoryStatusDTO dto) {
        categoryService.updateStatus(id, dto.getStatus());
        return R.success();
    }

    @PutMapping("/{id}/sort")
    public R<Void> updateSort(
            @PathVariable String id,
            @RequestBody @Validated CategorySortDTO dto) {
        categoryService.updateSort(id, dto.getSort());
        return R.success();
    }
}